﻿Public Class FEditShare
    Private mShare As Entities.Share

    Public Shared Sub CreateNew(ByVal owner As IWin32Window)
        Dim clsNew As New Entities.Share
        clsNew.SecurityGroupIds = New HashSet(Of Integer)
        clsNew.SecurityGroupIds.Add(Framework.Security.Manager.GetByTypeAndSubType(Entities.SecurityGroupType.System, Entities.SecurityGroupSubType.AuthenticatedUsers).Id)
        Edit(owner, clsNew)
    End Sub
    Public Shared Sub CreateNew(ByVal owner As IWin32Window, ByVal template As Entities.Share)
        Dim clsNew As New Entities.Share
        clsNew.GroupMode = template.GroupMode
        clsNew.ItemTypes = template.ItemTypes
        clsNew.Name = template.Name
        clsNew.Paths.AddRange(template.Paths.ToArray)
        clsNew.SecurityGroupIds = New HashSet(Of Integer)(template.SecurityGroupIds.ToArray)
        Edit(owner, clsNew)
    End Sub

    Public Shared Sub Edit(ByVal owner As IWin32Window, ByVal share As Entities.Share)
        Dim clsView As New FEditShare
        clsView.ShowIt(owner, share)
    End Sub

    Private Sub ShowIt(ByVal owner As IWin32Window, ByVal shareToEdit As Entities.Share)
        mShare = shareToEdit

        cboGroupMode.Items.Add(Entities.GroupMode.IndividualFiles)
        cboGroupMode.Items.Add(Entities.GroupMode.GroupSubDirectories)
        cboGroupMode.Items.Add(Entities.GroupMode.GroupIdenticalExtensionlessFilenames)

        cboItemTypes.Items.Add(Entities.ItemType.Files)
        cboItemTypes.Items.Add(Entities.ItemType.Movies)
        'cboItemTypes.Items.Add(Entities.ItemType.MusicAlbums)
        'cboItemTypes.Items.Add(Entities.ItemType.MusicFiles)
        'cboItemTypes.Items.Add(Entities.ItemType.TVSeries)

        txtName.Text = shareToEdit.Name
        If shareToEdit.Paths IsNot Nothing Then
            For Each strPath As String In shareToEdit.Paths
                lvwPaths.Items.Add(strPath)
            Next
        End If

        If shareToEdit.Id = 0 Then 'new
            chkRecursive.Checked = True
            cboItemTypes.SelectedItem = Entities.ItemType.Movies
            cboGroupMode.SelectedItem = Entities.GroupMode.GroupIdenticalExtensionlessFilenames
            Me.Text = "Create new share - Buddy 2 Buddy"
        Else
            chkRecursive.Checked = shareToEdit.Recursive
            cboItemTypes.SelectedItem = shareToEdit.ItemTypes
            cboGroupMode.SelectedItem = shareToEdit.GroupMode
            Me.Text = String.Format("{0} - Edit Share - Buddy 2 Buddy", shareToEdit.Name)
        End If
        For Each clsG As Entities.SecurityGroup In Framework.Security.Manager.GetAll
            If shareToEdit.SecurityGroupIds.Contains(clsG.Id) Then
                AddGroup(clsG)
            End If
        Next
        Me.Icon = Framework.My.Resources.Share
        MyBase.Show()
    End Sub

    Private Class GroupHolder
        Public ReadOnly Group As Entities.SecurityGroup
        Public Sub New(ByVal group As Entities.SecurityGroup)
            Me.Group = group
        End Sub
        Public Overrides Function ToString() As String
            Return Group.Name
        End Function
    End Class

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        If Save Then Me.Close()
    End Sub

    Private Function Save() As Boolean
        Try
            Error_Clear()

            If txtName.Text.Trim.Length = 0 Then Error_Set(txtName, "Name must be filled in!")
            If lvwPaths.Items.Count = 0 Then
                Error_Set(lvwPaths, "Atleast one path must be added!")
            Else
                For Each clsItem As ListViewItem In lvwPaths.Items
                    Dim strPath As String = CStr(clsItem.Text)
                    If Not IO.Directory.Exists(strPath) Then
                        Error_Set(lvwPaths, String.Format("The path ""{0}"" does not exist or is unavailable!", strPath))
                    End If
                Next
            End If

            If mAnyError Then Return False

            mShare.GroupMode = CType(cboGroupMode.SelectedItem, Entities.GroupMode)
            mShare.ItemTypes = CType(cboItemTypes.SelectedItem, Entities.ItemType)
            mShare.Name = txtName.Text
            mShare.Paths = GetSelectedPaths
            mShare.Recursive = chkRecursive.Checked
            mShare.SecurityGroupIds = GetSelectedGroupIds()

            EntityHandlers.Shares.Save(mShare)
            Engine.Manager.RescanShare(mShare, TimeSpan.FromSeconds(5))
            Return True
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
            Return False
        End Try
    End Function



    Private Function GetSelectedPaths() As Generic.List(Of String)
        Dim aRet As New Generic.List(Of String)
        For Each clsItem As ListViewItem In lvwPaths.Items
            aRet.Add(clsItem.Text)
        Next
        Return aRet
    End Function

    Private mAnyError As Boolean = False
    Private Sub Error_Clear()
        mAnyError = False
        ErrorProvider1.Clear()
    End Sub
    Private Sub Error_Set(ByVal control As Control, ByVal text As String)
        If Not mAnyError Then
            mAnyError = True
            control.Focus()
        End If
        Dim strExistingErrorText As String = ErrorProvider1.GetError(control)
        If String.IsNullOrEmpty(strExistingErrorText) Then
            ErrorProvider1.SetError(control, text)
        Else
            ErrorProvider1.SetError(control, strExistingErrorText & vbNewLine & text)
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try

            FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop ' Environment.SpecialFolder.MyComputer

            Dim strCurrentPath As String = txtName.Text
            While Not IO.Directory.Exists(strCurrentPath) And strCurrentPath.Length > 0
                strCurrentPath = IO.Path.GetDirectoryName(strCurrentPath)
            End While
            FolderBrowserDialog1.SelectedPath = strCurrentPath
            FolderBrowserDialog1.ShowNewFolderButton = True
            FolderBrowserDialog1.Description = "Select folder to add to your share"

            Select Case FolderBrowserDialog1.ShowDialog(Me)
                Case Windows.Forms.DialogResult.OK
                    lvwPaths.Items.Add(FolderBrowserDialog1.SelectedPath)
                    If txtName.Text.Trim.Length = 0 Then
                        txtName.Text = IO.Path.GetFileName(FolderBrowserDialog1.SelectedPath)
                    End If
            End Select
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        Try
            lvwPaths.Items.Clear()
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        Try
            For i As Integer = lvwPaths.SelectedItems.Count - 1 To 0 Step -1
                lvwPaths.SelectedItems(i).Remove()
            Next
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub AddGroup(ByVal group As Entities.SecurityGroup)
        With lvwGroupMembership.Items.Add(group.Name)
            .Tag = group
        End With
    End Sub

    Private Sub btnAddGroup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddGroup.Click
        Try
            Dim clsOpts As New Framework.Security.SelectGroupOptions
            clsOpts.Caption = String.Format("Select new group for share {0}", txtName.Text)
            clsOpts.HideSecurityGroupIds = GetSelectedGroupIds()
            For Each clsG As Entities.SecurityGroup In Framework.Security.Manager.SelectGroups(Me, clsOpts)
                AddGroup(clsG)
            Next
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Function GetSelectedGroupIds() As Generic.HashSet(Of Integer)
        Dim aRet As New Generic.HashSet(Of Integer)
        For Each clsItem As System.Windows.Forms.ListViewItem In lvwGroupMembership.Items
            Dim clsG As Entities.SecurityGroup = CType(clsItem.Tag, Entities.SecurityGroup)
            aRet.Add(clsG.Id)
        Next
        Return aRet
    End Function

    Private Sub btnRemoveGroup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveGroup.Click
        Try
            While lvwGroupMembership.SelectedItems.Count > 0
                lvwGroupMembership.SelectedItems(0).Remove()
            End While
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
End Class